//
//  CarSafeRangeMgr.m
//  carcareIOS
//
//  Created by ileo on 15/7/14.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "CarFenceMgr.h"
#import "NetCarFence.h"
#import "CalendarMgr.h"

@implementation CarFenceModel

-(id)initWithDic:(NSDictionary *)dic{
    self = [super initWithDic:dic];
    if (self) {
        self.cid = [dic[@"id"] integerValue];
        self.showTime = [CALENDARMGR dateStrWithDate:[CALENDARMGR dateWithStr:self.cdt format:@"yyyy-MM-dd HH:mm:ss"] format:@"yyyy年MM月dd日"];
    }
    return self;
}

-(NSDictionary *)modelDic{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[super modelDic]];
    [dic setObject:@(self.cid) forKey:@"id"];
    [dic removeObjectsForKeys:@[@"cid",@"showTime",@"coordinate"]];
    return dic;
}

-(CLLocationCoordinate2D)coordinate{
    return CLLocationCoordinate2DMake(self.lat, self.lng);
}

-(void)setCoordinate:(CLLocationCoordinate2D)coordinate{
    self.lat = coordinate.latitude;
    self.lng = coordinate.longitude;
}

@end

@implementation CarFenceMgr

IMP_SINGLETON

+(void)updateFencesFinish:(void (^)())finish{
    [[[NetCarFence carFenceDatas] requestWithLoad:RequestLoadShowLoading|RequestLoadShowErrorTips] requestSuccess:^(id JSON) {
        NSArray *tmp = JSON[@"list"];
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:tmp.count];
        for (int i = 0; i < tmp.count; i++) {
            CarFenceModel *model = [[CarFenceModel alloc] initWithDic:tmp[i]];
            [models addObject:model];
        }
        [CarFenceMgr sharedInstance].fences = models;
        if (finish) {
            finish();
        }
    }];
}

+(void)addFence:(CarFenceModel *)model finish:(void (^)(id))finish{
    [[[NetCarFence carFenceAddData:model.modelDic] requestWithLoad:RequestLoadShowLoading|RequestLoadShowErrorTips] requestSuccess:finish];
}

+(void)modityFence:(CarFenceModel *)model finish:(void (^)())finish{
    [[[NetCarFence carFenceModityData:model.modelDic] requestWithLoad:RequestLoadShowLoading|RequestLoadShowErrorTips] requestSuccess:^(id JSON) {
        if (finish) {
            finish();
        }
    }];
}

+(void)removeFence:(CarFenceModel *)model finish:(void (^)())finish{
    [[[NetCarFence carFenceDeleteDataWithID:model.cid] requestWithLoad:RequestLoadShowLoading|RequestLoadShowErrorTips] requestSuccess:^(id JSON) {
        NSMutableArray *tmp = [NSMutableArray arrayWithArray:[CarFenceMgr sharedInstance].fences];
        [tmp removeObject:model];
        [CarFenceMgr sharedInstance].fences = tmp;
        if (finish) {
            finish();
        }
    }];
}

@end
